package com.lanyou.esb.cook.proxy.dao.impl;

import java.util.ArrayList;
import java.util.List;

import com.lanyou.esb.cook.proxy.entity.TraceLog;

/**
 * 跟踪日志持久层
 * 
 * @author Davey.wu
 */
public class TraceLogDao extends BaseDao<TraceLog> {
	private static final List<String> fields = new ArrayList<String>();
	/** SQL **/
	private static final String SQL;
	static {
		fields.add("TRACE_LOG_ID");
		fields.add("IF_HTTP_ID");
		fields.add("CALL_SYSTEM_CODE");
		fields.add("TRACE_MSG");

		fields.add("IS_ENABLE");
		fields.add("CREATOR");
		fields.add("CREATED_DATE");
		fields.add("MODIFIER");
		fields.add("LAST_UPDATED_DATE");
	}
	static {
		StringBuilder builderFields = new StringBuilder();
		StringBuilder builderValues = new StringBuilder();
		builderFields.append(" (");
		builderValues.append(" (");
		int size = fields.size();
		for (int i = 0; i < size; ++i) {
			builderFields.append(fields.get(i) + (i == size - 1 ? "" : ","));
			builderValues.append((i == size - 1 ? "?" : "?,"));
		}
		builderFields.append(") ");
		builderValues.append(") ");
		SQL = "insert into T_ESB_BU_IF_TRACE_LOG" + builderFields.toString()
				+ " values " + builderValues.toString();
	}

	@Override
	public int save(TraceLog traceLog) {
		return getJdbcTemplate().update(SQL, traceLog.getId(),
				traceLog.getIfId(), traceLog.getCallSystemCode(),
				traceLog.getTraceMsg(), traceLog.getIsEnable(),
				traceLog.getCreator(), traceLog.getCreatedDate(),
				traceLog.getModifier(), traceLog.getLastUpdatedDate());
	}

	@Override
	public int saveAll(List<TraceLog> list) {
		if (list == null || list.isEmpty()) {
			return 0;
		}
		List<Object[]> args = new ArrayList<>();
		int i = 0;
		for (TraceLog log : list) {
			i = 0;
			Object[] objects = new Object[fields.size()];
			objects[i++] = log.getId();
			objects[i++] = log.getIfId();
			objects[i++] = log.getCallSystemCode();
			String msg = log.getTraceMsg();
			if (msg != null && msg.length() > 500) {
				// 跟踪信息不能超过500,因为出错信息排在后面，所以取后500个字符
				msg = msg.substring(msg.length() - 500);
			}
			objects[i++] = msg;
			objects[i++] = log.getIsEnable();
			objects[i++] = log.getCreator();
			objects[i++] = log.getCreatedDate();
			objects[i++] = log.getModifier();
			objects[i++] = log.getLastUpdatedDate();
			args.add(objects);
		}
		int[] result = getJdbcTemplate().batchUpdate(SQL, args);
		int num = 0;
		for (int k : result) {
			num += k;
		}
		return num;
	}
}
